package simulation;

import java.util.Vector;

import person.PersonAchive;
import schedule.Schedule;
import schedule.ScheduleBuilder;
import action.concreteActions.TerminalAction;

public class SimRunner {
	public static String currentDate;
	private static Vector<Thread> sThreads = new Vector<Thread>();

	public static void runSimulation(String date) {
		currentDate = date;
		Vector<ScheduleRunner> threads = new Vector<ScheduleRunner>();
		for (int i = 0; i < PersonAchive.getCount(); i++) {
			Schedule s = ScheduleBuilder.buildSchedule(PersonAchive
					.getPerson(i).getName(), date);
			ScheduleRunner sr = new ScheduleRunner();
			sr.init(s, i);
			threads.add(sr);
			try {
				PersonAchive.getPerson(i).setInHouse(true);
				PersonAchive.getPerson(i).setCurrentLocation(
						((TerminalAction) s.get(0)).getLocation());
			} catch (Exception e) {
				System.out.println(PersonAchive.getPerson(i).getName());
				e.printStackTrace();
				System.out.println("Initialization error");
				System.exit(1);
			}
		}
		Schedule s = ScheduleBuilder.buildSchedule("Weather", date);
		ScheduleRunner sr = new ScheduleRunner();
		sr.init(s, PersonAchive.getCount());
		threads.add(sr);
		sThreads = new Vector<Thread>();
		DataCollector dc = new DataCollector(currentDate);
		dataThread = new Thread(dc);
		ScheduleProgram.initAccess(PersonAchive.getCount() + 1);
		for (int i = 0; i < threads.size(); i++) {
			Thread scheduleThread = new Thread(threads.get(i));
			sThreads.add(scheduleThread);
			scheduleThread.start();
		}
		dataThread.start();

	}

	private static Thread dataThread;

	public static void StopSimulation() {
		try {
			dataThread.stop();
			for (int i = 0; i < sThreads.size(); i++) {
				sThreads.get(i).stop();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
